﻿//using MongoDB.Bson;
//using MongoDB.Driver;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using System.Linq.Expressions;
//using System.Collections;
//using System.Reflection;

//namespace MongodbClass
//{
//    /// <summary>
//    /// Mongodb操作类
//    /// </summary>
//    public class MongoHelper
//    {
//        private string MongDBip = string.Empty;
//        private string MongDBname = string.Empty;
//        public MongoHelper()
//        { }
//        public MongoHelper(string MongDBip, string MongDBname)
//        {
//            this.MongDBip = MongDBip;
//            this.MongDBname = MongDBname;
//        }
//        private IMongoDatabase database(string MongDBip, string MongDBname)
//        {
//            var client = new MongoClient(MongDBip);
//            return client.GetDatabase(MongDBname);
//        }

//        private string getTabName<T>()
//        {
//            var atts = typeof(T).CustomAttributes;
//            var att = atts.FirstOrDefault(t => t.AttributeType.FullName == "System.ComponentModel.DataAnnotations.Schema.TableAttribute");
//            if (att == null)
//                return string.Empty;

//            var name = att.ConstructorArguments.FirstOrDefault();
//            if (name == null)
//                return string.Empty;
//            return name.Value as string;
//        }

//        /// <summary>
//        /// 批量添加操作
//        /// </summary>
//        public void Insert(IEnumerable<BsonDocument> datas, string tableName, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<BsonDocument>(tableName);
//            collection.InsertMany(datas);
//        }


//        /// <summary>
//        /// 批量添加操作
//        /// </summary>
//        public void InsertArray<T>(IEnumerable<T> datas, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            collection.InsertMany(datas);
//        }


//        /// <summary>
//        /// 单个添加操作
//        /// </summary>
//        public void Insert(BsonDocument data, string tableName, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<BsonDocument>(tableName);
//            collection.InsertOne(data);
//        }

//        /// <summary>
//        /// 单个添加操作
//        /// </summary>
//        public void Insert<T>(T data, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (data is IEnumerable<BsonDocument>)
//            {
//                this.Insert(data as IEnumerable<BsonDocument>, tableName, DBip, DBname);
//                return;
//            }
//            else if (data is IEnumerable)
//            {
//                var array = data as IEnumerable;
//                var enumer = array.GetEnumerator();
//                if (enumer.MoveNext())
//                {
//                    var methodinfo = this.GetType().GetMethod("InsertArray", BindingFlags.Instance | BindingFlags.Public);
//                    methodinfo.MakeGenericMethod(enumer.Current.GetType()).Invoke(this, new object[] { data, tableName, DBip, DBname });
//                }
//                return;
//            }
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            collection.InsertOne(data);
//        }
//        /// <summary>
//        /// 条件（字段控制）查询操作
//        /// </summary>
//        public dynamic Find(string tableName, BsonDocument where, BsonDocument fields, string DBip = null, string DBname = null)
//        {

//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.Find(where).Project<dynamic>(fields).ToList();
//        }
//        /// <summary>
//        /// 条件（字段控制、排序、条数、第几条）查询操作
//        /// </summary>
//        public dynamic FindAll(string tableName, BsonDocument where, BsonDocument fields, SortDefinition<dynamic> sort, int? limit = null, int? skip = null, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.Find(where).Project<dynamic>(fields).Sort(sort).Limit(limit).Skip(skip).ToList();
//        }

//        /// <summary>
//        /// 条件（字段控制）查询操作
//        /// </summary>
//        public IQueryable<T> Find<T>(Expression<Func<T, bool>> filter = null, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            if (filter == null)
//                return collection.AsQueryable();
//            return collection.AsQueryable().Where(filter);
//        }
//        /// <summary>
//        /// 查询全部操作
//        /// </summary>
//        public dynamic Find(string tableName, BsonDocument where, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.Find(where).ToList();
//        }
//        /// <summary>
//        /// 查询全部操作并且排序获取指定数量的数据
//        /// </summary>
//        public dynamic FindSort(string tableName, BsonDocument where, SortDefinition<dynamic> sort, int limit, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.Find(where).Sort(sort).Limit(limit).ToList();
//        }

//        /// <summary>
//        /// 批量查询
//        /// </summary>
//        /// <param name="tableName"></param>
//        /// <param name="where"></param>
//        /// <param name="DBip"></param>
//        /// <param name="DBname"></param>
//        /// <returns></returns>
//        public List<dynamic> FindList(string tableName, BsonDocument where, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.Find(where).ToList();
//        }


//        /// <summary>
//        /// 批量查询
//        /// </summary>
//        /// <param name="tableName"></param>
//        /// <param name="filter"></param>
//        /// <param name="DBip"></param>
//        /// <param name="DBname"></param>
//        /// <returns></returns>
//        public IList<T> FindList<T>(Expression<Func<T, bool>> filter = null, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);

//            if (filter == null)
//                return collection.AsQueryable().ToList();
//            return collection.AsQueryable().Where(filter).ToList();
//        }


//        /// <summary>
//        /// 批量删除操作
//        /// </summary>
//        public dynamic DeleteMany(string tableName, BsonDocument where, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.DeleteMany(where);
//        }

//        /// <summary>
//        /// 批量删除操作
//        /// </summary>
//        public long DeleteMany<T>(Expression<Func<T, bool>> filter, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            return collection.DeleteMany(filter).DeletedCount;
//        }

//        /// <summary>
//        /// 单个删除操作
//        /// </summary>
//        public dynamic DeleteOne(string tableName, BsonDocument where, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.DeleteOne(where);
//        }

//        /// <summary>
//        /// 单个更新操作
//        /// </summary>
//        public bool UpdateOne<T>(T ob, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            var where = new MongoDB.Driver.FilterDefinitionBuilder<T>();
//            var id = ob.GetValue<ObjectId>("_id");
//            var t = Expression.Parameter(typeof(T), "t");
//            Expression<Func<T, ObjectId>> field = (Expression<Func<T, ObjectId>>)Expression.Lambda(Expression.PropertyOrField(t, "_id"), t);
//            var re = collection.ReplaceOne(where.Eq(field, id), ob);
//            return re.MatchedCount > 0;
//        }

//        /// <summary>
//        /// 单个删除操作
//        /// </summary>
//        public long DeleteOne<T>(Expression<Func<T, bool>> filter, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            DeleteResult dr = collection.DeleteOne(filter);
//            return dr.DeletedCount;
//        }

//        /// <summary>
//        /// 单个更新操作
//        /// BsonDocument where = new BsonDocument();
//        /// where.Add("name", c.name);相当于sql  where后的条件
//        /// BsonDocument fifter = new BsonDocument();
//        /// fifter.Add("$set", new BsonDocument("title", c.title));相当于sql set后需要更新的字段
//        /// </summary>
//        public dynamic UpdateOne(string tableName, BsonDocument where, BsonDocument filter, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return collection.UpdateOne(where, filter);
//        }

//        /// <summary>
//        /// 批量更新操作
//        /// </summary>
//        public long Update<T>(Expression<Func<T, bool>> filter, UpdateDefinition<T> ud, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            return collection.UpdateMany(filter, ud).ModifiedCount;
//        }

//        /// <summary>
//        /// 批量更新操作
//        /// </summary>
//        public long Update<T>(Expression<Func<T, bool>> filter, T updateob, Expression<Func<T, IEnumerable<object>>> updatefields, string tableName = null, string DBip = null, string DBname = null)
//        {
//            if (string.IsNullOrEmpty(tableName))
//                tableName = getTabName<T>();
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            // var values = updatefields.Compile().Invoke(updateob);
//            var Expressions = ((System.Linq.Expressions.NewArrayExpression)updatefields.Body).Expressions;

//            UpdateDefinition<T> uds = null;
//            MethodInfo method = Builders<T>.Update.GetType().GetMethods().Where(t => t.Name == "Set" && t.GetParameters().Any(p => p.ParameterType.Name == "Expression`1")).First();
//            List<UpdateDefinition<T>> udlist = new List<UpdateDefinition<T>>();
//            foreach (var ee in Expressions)
//            {
//                Expression e = ee;
//                LambdaExpression ex = Expression.Lambda(e, updatefields.Parameters);
//                if (e is UnaryExpression && (e as UnaryExpression).NodeType == ExpressionType.Convert)
//                {
//                    e = (e as UnaryExpression).Operand;
//                    ex = Expression.Lambda(e, updatefields.Parameters);
//                }
//                var methodf = method.MakeGenericMethod(e.Type);
//                udlist.Add(methodf.Invoke(Builders<T>.Update, new object[] { ex, ex.Compile().DynamicInvoke(updateob) }) as UpdateDefinition<T>);
//            }
//            uds = Builders<T>.Update.Combine(udlist);
//            return collection.UpdateMany(filter, uds).ModifiedCount;
//        }


//        /// <summary>
//        /// 获取记录数操作
//        /// </summary>
//        public dynamic GetCollectionCount(string tableName, BsonDocument where, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            return Convert.ToInt32(collection.Count(where));
//        }

//        /// <summary>
//        /// 获取记录数操作
//        /// </summary>
//        public long GetCollectionCount<T>(Expression<Func<T, bool>> filter = null, string tableName = null, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<T>(tableName);
//            if (filter == null)
//                return collection.AsQueryable().Count();
//            return Convert.ToInt32(collection.Count(filter));
//        }


//        /// <summary>
//        /// 分组获取记录集合
//        /// db.getCollection('CBF').aggregate([{$group: { _id: {$substr:["$CBFBM", 0, 4]}, num_tutorial: {$sum: 1} } }])
//        /// new BsonDocument { { "_id", new BsonDocument() { { "$substr", new BsonArray() { "$CBFBM", 0, 4 } } } }, { "Sum", new BsonDocument("$sum", 1) } };
//        /// </summary>
//        /// <param name="tableName"></param>
//        /// <param name="group"></param>
//        /// <param name="DBip"></param>
//        /// <param name="DBname"></param>
//        /// <returns></returns>
//        public dynamic GetCollectionGrop(string tableName, BsonDocument group, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            var aggregate = collection.Aggregate().Group(group);
//            return aggregate.ToList<BsonDocument>();
//        }
//        /// <summary>
//        /// 分组获取记录集合
//        /// db.getCollection('CBF').aggregate([{$group: { _id: {$substr:["$CBFBM", 0, 4]}, num_tutorial: {$sum: 1} } }])
//        /// new BsonDocument { { "_id", new BsonDocument() { { "$substr", new BsonArray() { "$CBFBM", 0, 4 } } } }, { "Sum", new BsonDocument("$sum", 1) } };
//        /// </summary>
//        /// <param name="tableName"></param>
//        /// <param name="filter"></param>
//        /// <param name="sort"></param>
//        /// <param name="group"></param>
//        /// <param name="DBip"></param>
//        /// <param name="DBname"></param>
//        /// <returns></returns>
//        public List<BsonDocument> GetCollectionGrop(string tableName, BsonDocument filter, SortDefinition<dynamic> sort, BsonDocument group, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            var aggregate = collection.Aggregate().Match(filter).Sort(sort).Group(group);
//            return aggregate.ToList<BsonDocument>();
//        }

//        /// <summary>
//        /// 分组获取记录集合
//        /// db.getCollection('CBF').aggregate([{$group: { _id: {$substr:["$CBFBM", 0, 4]}, num_tutorial: {$sum: 1} } }])
//        /// new BsonDocument { { "_id", new BsonDocument() { { "$substr", new BsonArray() { "$CBFBM", 0, 4 } } } }, { "Sum", new BsonDocument("$sum", 1) } };
//        /// </summary>
//        /// <param name="tableName"></param>
//        /// <param name="filter">过滤条件</param>
//        /// <param name="group">分组</param>
//        /// <param name="sort">排序</param>
//        /// <param name="project">输出</param>
//        /// <param name="DBip"></param>
//        /// <param name="DBname"></param>
//        /// <returns></returns>
//        public List<BsonDocument> GetCollectionGrop(string tableName, BsonDocument filter, BsonDocument group, BsonDocument project, SortDefinition<BsonDocument> sort, string DBip = null, string DBname = null)
//        {
//            var collection = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).GetCollection<dynamic>(tableName);
//            var aggregate = collection.Aggregate().Match(filter).Group(group).Project(project).Sort(sort).Limit(int.MaxValue);
//            return aggregate.ToList<BsonDocument>();
//        }

//        /// <summary>
//        /// 数据库中所有集合名
//        /// </summary>
//        /// <param name="DBip"></param>
//        /// <param name="DBname"></param>
//        /// <returns>集合名</returns>
//        public IList<string> GetCollectionsName(string DBip = null, string DBname = null)
//        {
//            var clist = database(DBip.IsNull(this.MongDBip), DBname.IsNull(this.MongDBname)).ListCollections();
//            var list = clist.ToList().Select(t => t["name"] + string.Empty).ToList();
//            return list;
//        }



//    }
//}


